package com.zh.netty.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * 群聊-客户端
 */
public class GroupChatClient01 {

    // 定义相关的属性
    private final String HOST = "127.0.0.1"; // 服务器的ip
    private final int PORT = 6667; // 服务器端口
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    // 构造器
    public GroupChatClient01() throws IOException {
        selector = Selector.open();

        // 连接服务器
        socketChannel = SocketChannel.open(new InetSocketAddress(HOST,PORT));
        // 设置非阻塞
        socketChannel.configureBlocking(false);
        // 将channel 注册到selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        // 得到username
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username + "is ok=========");
    }

    // 向服务器发送消息
    public void sendMsg(String msg){
        msg = username + ":"+ msg;
        try {
            socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    // 读取服务器端回复的消息
    public void readMsg(){
        try {
            int readChannels = selector.select(2000);
            if (readChannels > 0){ // 有可用的通道
                selector.selectedKeys().forEach(key -> {
                    if (key.isReadable()){ // 是可读的
                        // 得到相关通道
                        SocketChannel channel = (SocketChannel) key.channel();
                        // 得到一个buffer
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        try {
                            // 读取通道的消息到buffer
                            channel.read(byteBuffer);
                            String msg = new String(byteBuffer.array());
                            System.out.println("收到的消息："+msg.trim());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }else {
                        System.out.println("========没有可用的通道===========");
                    }
                    // 删除key,防止重复操作
                    selector.selectedKeys().remove(key);
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        // 启动客户端
        GroupChatClient01 groupChatClient = new GroupChatClient01();

        // 启动一个线程, 没隔3秒，读取从服务器端发送的数据
        new Thread(){
            @Override
            public  void  run(){
                while (true){
                    groupChatClient.readMsg();
                    try {
                        Thread.sleep(3000);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        // 发送数据给服务器端
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String s = scanner.nextLine();
            groupChatClient.sendMsg(s);
        }
    }
}
